#!/usr/bin/perl

use strict;
use Getopt::Long;
use LWP::UserAgent;
use HTTP::Cookies;
use HTTP::Status;
use Crypt::SSLeay;
use Term::ReadKey;
use Data::Dumper;

my ( $login_url, $ua, $secure_login_url, $username, $password );
my $cookie_file = "addama_lwp_cookies.dat"; 

if (@ARGV <= 0) {
  print "The domain url is required for login.  Example usage:\n  perl $0 http://yourhost\n";
  exit(0);
}

$login_url = $ARGV[0] . "/addama-login/login";
print "Using $login_url to login\n";

# get cookie jar ready
my $cookie_jar = HTTP::Cookies->new(
	file           => $cookie_file,
	ignore_discard => 1,
);

# init User agent
$ua = LWP::UserAgent->new;
$ua->agent("AddamaTestAgent/0.1 ");
$ua->cookie_jar($cookie_jar);

## Create a request
# initial request to get redirect
my $req1 = HTTP::Request->new( GET => $login_url );
my $res1 = $ua->simple_request($req1);

if ( $res1->is_error && $res1->status_line != 404) {
    print "Request failed: " . $res1->status_line . "\n";
    exit(-1);
} else {

    if ( is_redirect( $res1->code ) ) {
        $secure_login_url = $res1->header("location");
    } else {
        $secure_login_url = $login_url;
    }

    # try to authenticate
    print "\nEnter credentials at the following prompt. Credentials are sent securely.\n";
    my $code = _login();
    if ( status_message($code) =~ /unauthorized/i ) {
        print "login failed (wrong username, password combination). Try again? (Y/N): ", "\n";
        my $answer = $username = ReadLine;
        chomp $answer;
        if ( $answer eq "Y" or $answer eq "y" ) {
            _login();
        }
    }
    $cookie_jar->scan( \&_select_cookies );
    $cookie_jar->save();

    _clean_cookie_file($cookie_file);

}

# via curl this would be: curl -vik -X POST -d @login_creds  https://<addama URL>:<secure port>/addama-login/login
sub _login () {
	## get creds from user
	print "Enter your login name: \n";
	$username = ReadLine;
	chomp $username;
	print "Enter your password (will not display in command-line): \n";
	ReadMode 'noecho';
	$password = ReadLine, ReadMode 'normal';
	chomp $password;

	# try to authenticate
	my $req = HTTP::Request->new( POST => $secure_login_url );
	$req->content_type('application/x-www-form-urlencoded');
	$req->content(qq(username=$username&password=$password));
	my $res = $ua->request($req);

	# Check the outcome of the response
	if ( $res->is_success ) {

		# tell the user
		print "Login successful. Cookies will be updated.\n";
		return $HTTP::Status::RC_OK;
	}
	else {
		return $res->code;
	}
}

sub _select_cookies () {
	my @data = @_;
    return @data;
}


sub _clean_cookie_file {
    my $cookie_file = shift;
    print "Cleaning file $cookie_file\n";

    my $tmp_file = $cookie_file . ".tmp";
    open(IN, $cookie_file) or die "Failed to open cookie file $cookie_file: $!";

    my $cleaned;
    while (<IN>) {
        $_ =~ s/\\|"//g;
        $cleaned .= $_;
    }
    close(IN);

    # replace text in cookie file with cleaned text
    open(OUT, ">$cookie_file") or die "Failed to open cookie file to write: $!";
    print OUT $cleaned;
    close(OUT);
}
